/*
  Name:        test04.Convert.pixel.to.data.cpp
  Copyright:   Version 0.1
  Author:      Rodrigo Luis de Souza da Silva
  Date:        04/07/2009
  Description: Create an image from a pixel matrix.
*/

#include "pixelMap.h"
#ifdef WIN32
#include <windows.h>
#endif
#include <GL/glut.h>
#include <stdlib.h>

// Image Object
PixelMap *img = NULL;

void idle()
{
   glutPostRedisplay();
}

static void display(void)
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   int i, j;

   if(img)
   {
      pixel **pixels;
      // Aloca dinamicamente as linhas da matriz
      pixels = (pixel **) malloc(img->GetHeight() * sizeof(pixel *));
      // Aloca dinamicamente as colunas da matriz
      for(i = 0; i < img->GetHeight(); i++)
         pixels[i] = (pixel *) malloc(img->GetWidth() * sizeof(pixel));

      for(i = 0; i < img->GetHeight(); i++)
         for(j = 0; j < img->GetWidth(); j++)
         {
            pixels[i][j].R = 255;
            pixels[i][j].G = 50;
            pixels[i][j].B = 50;
            if(i > img->GetHeight()/2)
            {
               pixels[i][j].R = 255;
               pixels[i][j].G = 255;
               pixels[i][j].B = 50;
            }
         }
      img->ConvertPixelsToData(pixels);
      img->ViewImage();
   }
   glutSwapBuffers();
}

static void key(unsigned char key, int x, int y)
{
    switch (key)
    {
        case 27 :
        case 'q':
            exit(0);
        break;
    }
    glutPostRedisplay();
}

int main(int argc, char *argv[])
{
   glutInit(&argc, argv);

   int w = 400;
   int h = 400;
	unsigned size(w * h * 3); // size of the image in bytes (3 is to RGB component).
	uByte *data = new uByte[size];

   img = new PixelMap();
   img->CreateImage(w, h, data);

   glutInitWindowSize(img->GetWidth(),img->GetHeight());
   glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

   glutCreateWindow("Convert Pixel to Data test");

   glutKeyboardFunc(key);
   glutIdleFunc( idle);
   glutDisplayFunc(display);

   glutMainLoop();

   return 1;
}
